package com.laowang.project.common.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.laowang.common.constant.Constants;
import com.laowang.common.utils.StringUtils;
import com.laowang.common.utils.file.FileUploadUtils;
import com.laowang.common.utils.file.FileUtils;
import com.laowang.framework.config.RuoYiConfig;
import com.laowang.framework.config.ServerConfig;
import com.laowang.framework.web.domain.AjaxResult;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * 通用请求处理
 *
 * @author laowang
 */

@RestController
public class CommonController {

    public final static String img_path = "/www/wwwroot/wx.hubeixiangxiang.com/images/";
    //public final static String img_path = "D:\\img\\";

    public final static String domainNow = "https://wx.hubeixiangxiang.com/";

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String name, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(name)) {
                throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", name));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(name, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 酒店后台通用图片上传
     *
     * @param file
     */
    @RequestMapping(value = "/img/upload", method = {RequestMethod.POST})
    public AjaxResult upload( MultipartFile file) {
        if (Objects.isNull(file)){
            throw new CustomException("上传的文件不能为空",400);
        }
        String fileName = getFileName(file.getOriginalFilename());
        try {
            // 得到目录加上文件名
            fileName = writeFile(file.getInputStream(), fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(fileName)) {
            return AjaxResult.error("图片上传失败");
        }
        // 得到相对服务器上的路径
        fileName = getUrl(fileName);
        return AjaxResult.success("上传成功", fileName);

    }

    public String getUrl(String fileName){
        String uri = domainNow + "images/";
        return uri + fileName;
    }


    public String getFileName(String originalFileName) {
        String d = originalFileName.substring(originalFileName.lastIndexOf('.') + 1);
        String s = org.springframework.util.StringUtils.replace(UUID.randomUUID().toString(), "-", "");
        return s + "." + d;
    }

    public static String writeFile(InputStream inputStream, String fileName) {
        FileOutputStream fileOutputStream = null;
        try {
            String directory = DateUtils.getFormatDate(DateUtils.getCurrentTime(), "yyyyMMdd");
            File file = getFile(directory, fileName);
            fileOutputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int n = 0;
            while ((n = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, n);
            }
            fileOutputStream.close();
            return directory + "/" + fileName;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return "";
    }


    public static File getFile(String directory, String fileName) {
        try {
            String path = img_path + directory + "/";
            File directoryFile = new File(path);
            if (!directoryFile.exists()) {
                directoryFile.mkdirs();
            }
            path = path + fileName;
            File file = new File(path);
            return file;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }
}
